package com.example.xiaoshuo_yudu.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.xiaoshuo_yudu.entity.Result;
import com.example.xiaoshuo_yudu.entity.dto.BooksUpdateDTO;
import com.example.xiaoshuo_yudu.entity.entity.Books;
import com.example.xiaoshuo_yudu.service.BooksService;
import com.example.xiaoshuo_yudu.service.impl.BooksServiceImpl;
import io.swagger.v3.oas.annotations.Operation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员书籍管理控制器
 */
@RestController
@RequestMapping("/api/admin/books")
public class AdminBooksController {
    private static final Logger logger = LoggerFactory.getLogger(AdminBooksController.class);
    @Autowired
    private BooksServiceImpl booksService;
    /**
     * 分页查询小说列表
     * @param pageNum 页码，默认为1
     * @param pageSize 每页大小，默认为10
     * @param keyword 搜索关键词（可选）
     * @return 分页结果
     */
    @GetMapping("/list")
    @Operation(summary = "分页查询小说列表")
    public Result<Map<String, Object>> listBooks(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword) {
        
        logger.info("Fetching books list - pageNum: {}, pageSize: {}, keyword: {}", pageNum, pageSize, keyword);
        
        // 使用MyBatis Plus的分页功能
        Page<Books> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Books> queryWrapper = new QueryWrapper<>();
        if (keyword != null && !keyword.isEmpty()) {
            queryWrapper.and(wrapper -> wrapper
                    .like("novel_name", keyword)
                    .or()
                    .like("author", keyword)
                    .or()
                    .like("category", keyword));
        }
        queryWrapper.orderByAsc("book_id");
        
        Page<Books> resultPage = booksService.page(page, queryWrapper);
        List<Books> booksList = resultPage.getRecords();
        long total = resultPage.getTotal();
        
        Map<String, Object> data = new HashMap<>();
        data.put("list", booksList);
        data.put("total", total);
        
        logger.info("Found {} books, total: {}", booksList.size(), total);
        return Result.success(data);
    }

    /**
     * 添加书籍
     * @param booksUpdateDTO 书籍信息
     * @return 添加结果
     */
    @PostMapping("/add")
    public Result<Void> addBook(@RequestBody BooksUpdateDTO booksUpdateDTO) {
        Books books = new Books();
        BeanUtils.copyProperties(booksUpdateDTO, books);
        books.setCreateTime(LocalDateTime.now());
        books.setUpdateDbTime(LocalDateTime.now());
        
        if (booksService.save(books)) {
            return Result.success();
        } else {
            return Result.failure(500, "添加书籍失败");
        }
    }

    /**
     * 更新书籍信息
     * @param booksUpdateDTO 书籍信息
     * @return 更新结果
     */
    @PutMapping("/update")
    public Result<Void> updateBook(@RequestBody BooksUpdateDTO booksUpdateDTO) {
        if (booksUpdateDTO.getBookId() == null) {
            return Result.failure(400, "书籍ID不能为空");
        }
        
        Books books = booksService.getById(booksUpdateDTO.getBookId());
        if (books == null) {
            return Result.failure(404, "书籍不存在");
        }
        
        BeanUtils.copyProperties(booksUpdateDTO, books);
        books.setUpdateDbTime(LocalDateTime.now());
        
        if (booksService.updateById(books)) {
            return Result.success();
        } else {
            return Result.failure(500, "更新书籍失败");
        }
    }

    /**
     * 删除书籍
     * @param bookId 书籍ID
     * @return 删除结果
     */
    @DeleteMapping("/delete/{bookId}")
    public Result<Void> deleteBook(@PathVariable Integer bookId) {
        if (booksService.removeById(bookId)) {
            return Result.success();
        } else {
            return Result.failure(500, "删除书籍失败");
        }
    }

    /**
     * 批量删除书籍
     * @param bookIds 书籍ID列表
     * @return 删除结果
     */
    @DeleteMapping("/batch-delete")
    public Result<Void> batchDeleteBooks(@RequestBody List<Integer> bookIds) {
        if (booksService.removeBatchByIds(bookIds)) {
            return Result.success();
        } else {
            return Result.failure(500, "批量删除书籍失败");
        }
    }

    /**
     * 根据ID获取书籍详情
     * @param bookId 书籍ID
     * @return 书籍详情
     */
    @GetMapping("/detail/{bookId}")
    public Result<Books> getBookDetail(@PathVariable Integer bookId) {
        Books books = booksService.getById(bookId);
        if (books != null) {
            return Result.success(books);
        } else {
            return Result.failure(404, "书籍不存在");
        }
    }
}